<script setup lang="ts">
import type {
  GlobalMetric,
  MetricData,
  RateLimitConfig,
  RateLimitStats,
} from '#/api';

import { onMounted, reactive, ref } from 'vue';

import { useVbenVxeGrid } from '@vben/plugins/vxe-table';

import {
  Button,
  Card,
  Col,
  Descriptions,
  DescriptionsItem,
  Input,
  message,
  Modal,
  Row,
  Space,
  Statistic,
  Switch,
  Tag,
  Tooltip,
} from 'ant-design-vue';
import {
  Activity,
  BarChart3,
  Database,
  RefreshCw,
  Trash2,
} from 'lucide-vue-next';

import {
  clearAllRateLimitApi,
  clearMetricsApi,
  clearRateLimitApi,
  getAllKeysApi,
  getAllMetricsApi,
  getGlobalMetricsApi,
  getRateLimitConfigApi,
  getRateLimitStatsApi,
} from '#/api';

// 限流配置
const config = ref<RateLimitConfig>({
  enabled: false,
  defaultLimit: 0,
  ipLimit: 0,
  userLimit: 0,
  pathLimits: {},
  whiteList: [],
});

// 统计信息
const stats = ref<RateLimitStats>({
  totalKeys: 0,
  ipLimitKeys: 0,
  userLimitKeys: 0,
  pathLimitKeys: 0,
  defaultLimitKeys: 0,
});

// 全局指标
const globalMetric = ref<GlobalMetric>({
  totalRequests: 0,
  allowedRequests: 0,
  blockedRequests: 0,
  blockRate: 0,
});

// 所有指标
const allMetrics = ref<Record<string, MetricData>>({});

// 限流键列表
const rateLimitKeys = ref<string[]>([]);

// 加载状态
const loading = ref(false);
const configLoading = ref(false);
const statsLoading = ref(false);
const metricsLoading = ref(false);

// 查询参数
const queryParams = reactive({
  searchKey: '',
});

// 表格配置
const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions: {
    data: [],
    loading: false,
    pagerConfig: {
      enabled: false, // 禁用分页
    },
    columns: [
      {
        field: 'key',
        title: '限流键',
        minWidth: 200,
        slots: { default: 'key' },
      },
      {
        field: 'totalRequests',
        title: '总请求数',
        width: 120,
        align: 'center',
      },
      {
        field: 'allowedRequests',
        title: '允许请求数',
        width: 120,
        align: 'center',
      },
      {
        field: 'blockedRequests',
        title: '拒绝请求数',
        width: 120,
        align: 'center',
      },
      {
        field: 'blockRate',
        title: '拒绝率',
        width: 120,
        align: 'center',
        slots: { default: 'blockRate' },
      },
      {
        field: 'lastAccessTime',
        title: '最后访问时间',
        width: 180,
      },
      {
        field: 'action',
        title: '操作',
        width: 100,
        align: 'center',
        fixed: 'right',
        slots: { default: 'action' },
      },
    ],
  },
});

// 获取限流配置
async function fetchConfig() {
  try {
    configLoading.value = true;
    const result = await getRateLimitConfigApi();
    config.value = result || {
      enabled: false,
      defaultLimit: 0,
      ipLimit: 0,
      userLimit: 0,
      pathLimits: {},
      whiteList: [],
    };
  } catch (error) {
    console.error('获取限流配置失败:', error);
  } finally {
    configLoading.value = false;
  }
}

// 获取统计信息
async function fetchStats() {
  try {
    statsLoading.value = true;
    const result = await getRateLimitStatsApi();
    stats.value = result || {
      totalKeys: 0,
      ipLimitKeys: 0,
      userLimitKeys: 0,
      pathLimitKeys: 0,
      defaultLimitKeys: 0,
    };
  } catch (error) {
    console.error('获取统计信息失败:', error);
  } finally {
    statsLoading.value = false;
  }
}

// 获取全局指标
async function fetchGlobalMetrics() {
  try {
    metricsLoading.value = true;
    const result = await getGlobalMetricsApi();
    globalMetric.value = result || {
      totalRequests: 0,
      allowedRequests: 0,
      blockedRequests: 0,
      blockRate: 0,
    };
  } catch (error) {
    console.error('获取全局指标失败:', error);
  } finally {
    metricsLoading.value = false;
  }
}

// 获取所有指标
async function fetchAllMetrics() {
  try {
    loading.value = true;
    const result = await getAllMetricsApi();
    allMetrics.value = result || {};

    // 转换为表格数据，添加默认值
    const tableData = Object.entries(result || {}).map(([key, value]) => ({
      key,
      totalRequests: value?.totalRequests || 0,
      allowedRequests: value?.allowedRequests || 0,
      blockedRequests: value?.blockedRequests || 0,
      blockRate: value?.blockRate || 0,
      lastAccessTime: value?.lastAccessTime || '-',
    }));

    // 应用搜索过滤
    const filteredData = queryParams.searchKey
      ? tableData.filter((item) =>
          item.key.toLowerCase().includes(queryParams.searchKey.toLowerCase()),
        )
      : tableData;

    // 使用 setState 设置表格数据
    gridApi.setState({
      gridOptions: {
        data: filteredData,
        loading: false,
      },
    });
  } catch (error) {
    console.error('获取所有指标失败:', error);
    gridApi.setState({
      gridOptions: {
        data: [],
        loading: false,
      },
    });
  } finally {
    loading.value = false;
  }
}

// 获取所有限流键
async function fetchAllKeys() {
  try {
    const result = await getAllKeysApi();
    rateLimitKeys.value = result || [];
  } catch (error) {
    console.error('获取限流键失败:', error);
    rateLimitKeys.value = [];
  }
}

// 刷新所有数据
async function handleRefresh() {
  await Promise.all([
    fetchConfig(),
    fetchStats(),
    fetchGlobalMetrics(),
    fetchAllMetrics(),
    fetchAllKeys(),
  ]);
  message.success('刷新成功');
}

// 搜索
function handleSearch() {
  fetchAllMetrics();
}

// 重置搜索
function handleReset() {
  queryParams.searchKey = '';
  fetchAllMetrics();
}

// 清除指定键的限流记录
async function handleClearKey(key: string) {
  Modal.confirm({
    title: '确认清除',
    content: `确定要清除限流键 "${key}" 的记录吗？`,
    onOk: async () => {
      try {
        await clearRateLimitApi(key);
        message.success('清除成功');
        await handleRefresh();
      } catch (error) {
        console.error('清除失败:', error);
      }
    },
  });
}

// 清除所有限流记录
async function handleClearAll() {
  Modal.confirm({
    title: '确认清除',
    content: '确定要清除所有限流记录吗？此操作不可恢复！',
    okType: 'danger',
    onOk: async () => {
      try {
        const result = await clearAllRateLimitApi();
        message.success(result.message || '清除成功');
        await handleRefresh();
      } catch (error) {
        console.error('清除失败:', error);
      }
    },
  });
}

// 清除所有指标
async function handleClearMetrics() {
  Modal.confirm({
    title: '确认清除',
    content: '确定要清除所有指标数据吗？此操作不可恢复！',
    okType: 'danger',
    onOk: async () => {
      try {
        await clearMetricsApi();
        message.success('清除成功');
        await handleRefresh();
      } catch (error) {
        console.error('清除失败:', error);
      }
    },
  });
}

// 初始化
onMounted(() => {
  handleRefresh();
});
</script>

<template>
  <div class="h-full overflow-auto p-4">
    <!-- 统计卡片 -->
    <Row :gutter="16" class="mb-4">
      <Col :span="6">
        <Card :loading="metricsLoading">
          <Statistic title="总请求数" :value="globalMetric.totalRequests">
            <template #prefix>
              <Activity :size="20" class="text-blue-500" />
            </template>
          </Statistic>
        </Card>
      </Col>
      <Col :span="6">
        <Card :loading="metricsLoading">
          <Statistic
            title="允许请求数"
            :value="globalMetric.allowedRequests"
          >
            <template #prefix>
              <BarChart3 :size="20" class="text-green-500" />
            </template>
          </Statistic>
        </Card>
      </Col>
      <Col :span="6">
        <Card :loading="metricsLoading">
          <Statistic
            title="拒绝请求数"
            :value="globalMetric.blockedRequests"
          >
            <template #prefix>
              <Trash2 :size="20" class="text-red-500" />
            </template>
          </Statistic>
        </Card>
      </Col>
      <Col :span="6">
        <Card :loading="metricsLoading">
          <Statistic
            title="拒绝率"
            :value="globalMetric.blockRate"
            :precision="2"
            suffix="%"
            :value-style="{
              color: globalMetric.blockRate > 50 ? '#cf1322' : '#3f8600',
            }"
          >
            <template #prefix>
              <Database :size="20" class="text-orange-500" />
            </template>
          </Statistic>
        </Card>
      </Col>
    </Row>

    <!-- 限流配置 -->
    <Card title="限流配置" class="mb-4" :loading="configLoading">
      <Descriptions bordered :column="2">
        <DescriptionsItem label="限流开关">
          <Switch :checked="config.enabled" disabled />
        </DescriptionsItem>
        <DescriptionsItem label="默认限制">
          {{ config.defaultLimit }} 次/分钟
        </DescriptionsItem>
        <DescriptionsItem label="IP限制">
          {{ config.ipLimit }} 次/分钟
        </DescriptionsItem>
        <DescriptionsItem label="用户限制">
          {{ config.userLimit }} 次/分钟
        </DescriptionsItem>
        <DescriptionsItem label="路径限制" :span="2">
          <Space v-if="Object.keys(config.pathLimits).length > 0" wrap>
            <Tag
              v-for="(limit, path) in config.pathLimits"
              :key="path"
              color="blue"
            >
              {{ path }}: {{ limit }} 次/分钟
            </Tag>
          </Space>
          <span v-else class="text-gray-400">暂无配置</span>
        </DescriptionsItem>
        <DescriptionsItem label="白名单" :span="2">
          <Space v-if="config.whiteList.length > 0" wrap>
            <Tag v-for="ip in config.whiteList" :key="ip" color="green">
              {{ ip }}
            </Tag>
          </Space>
          <span v-else class="text-gray-400">暂无配置</span>
        </DescriptionsItem>
      </Descriptions>
    </Card>

    <!-- 统计信息 -->
    <Card title="统计信息" class="mb-4" :loading="statsLoading">
      <Row :gutter="16">
        <Col :span="8">
          <Statistic title="总限流键数" :value="stats.totalKeys" />
        </Col>
        <Col :span="8">
          <Statistic title="IP限流键数" :value="stats.ipLimitKeys" />
        </Col>
        <Col :span="8">
          <Statistic title="用户限流键数" :value="stats.userLimitKeys" />
        </Col>
      </Row>
      <Row :gutter="16" class="mt-4">
        <Col :span="8">
          <Statistic title="路径限流键数" :value="stats.pathLimitKeys" />
        </Col>
        <Col :span="8">
          <Statistic title="默认限流键数" :value="stats.defaultLimitKeys" />
        </Col>
      </Row>
    </Card>

    <!-- 限流指标列表 -->
    <Card title="限流指标" :bordered="false">
      <div class="mb-4">
        <Space>
          <Input
            v-model:value="queryParams.searchKey"
            placeholder="搜索限流键"
            allow-clear
            style="width: 300px"
            @press-enter="handleSearch"
          />
          <Button type="primary" @click="handleSearch">搜索</Button>
          <Button @click="handleReset">重置</Button>
          <Button @click="handleRefresh">
            <RefreshCw :size="16" class="mr-1" />
            刷新
          </Button>
          <Button danger @click="handleClearAll">
            <Trash2 :size="16" class="mr-1" />
            清除所有限流记录
          </Button>
          <Button danger @click="handleClearMetrics">
            <Trash2 :size="16" class="mr-1" />
            清除所有指标
          </Button>
        </Space>
      </div>

      <div style="height: 500px">
        <Grid class="h-full">
          <!-- 限流键列 -->
          <template #key="{ row }">
            <Tooltip :title="row.key">
              <Tag color="blue">{{ row.key }}</Tag>
            </Tooltip>
          </template>

          <!-- 拒绝率列 -->
          <template #blockRate="{ row }">
            <Tag :color="(row.blockRate || 0) > 50 ? 'red' : 'green'">
              {{ (row.blockRate || 0).toFixed(2) }}%
            </Tag>
          </template>

          <!-- 操作列 -->
          <template #action="{ row }">
            <Button
              type="link"
              size="small"
              danger
              @click="handleClearKey(row.key)"
            >
              清除
            </Button>
          </template>
        </Grid>
      </div>
    </Card>
  </div>
</template>

<style scoped>
/* 防止页面加载时的布局闪烁 */
.h-full {
  min-height: 100%;
}

:deep(.ant-statistic-title) {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.65);
}

:deep(.ant-statistic-content) {
  font-size: 24px;
  font-weight: 600;
}
</style>

